<?php
namespace Home\Model;

class ModelArticleModel extends ContentModel {
	
	/**
	 * 获得文章内容详细
	 * @param unknown $id 文章ID
	 */
	public function detail($cate = null, $id) {
		if($id && $modelArticle = M("ModelArticle")->find($id)) {
			$model = $this->getModel($modelArticle['category']);
			$model['modelName'] = $this->getModelName($model['tag']);
			$condition = array(
					"this0.customer" => $modelArticle['customer'],
					"this0.is_deleted" => 0,
					"this0.id" => $id,
			);
			$data = M()->table("__MODEL_ARTICLE__ this0")->join("LEFT JOIN __MODEL_ARTICLE_CONFIG__ this1 on this0.id=this1.id")->where($condition)->find();
			if($data)  $data ['tags'] = $this->getTagNames ( $data ['tags'], $data['customer'] );
			return array('data'=>$data, 'model' => $model);
		} else return array();
	}
	
	
	/**
	 * 获得当前栏目文章列表
	 * @param $cate 栏目id
	 * @param $paginate 是否启用分页
	 * @param $p 当前页
	 * @return 获得子栏列表
	 */
	public function lists($cate=0, $paginate=false, $pageSize=10, $p=1) {
		if($cate && $category = M("Category")->find($cate)) {
			$model = $this->getModel($cate);
			$tableName = $this->getTableName($model['tag']);
			$model['modelName'] = $this->getModelName($model['tag']);
			$extModelName = $this->getExtTableName($tableName);
			$tableName = '__'.strtoupper($tableName).'__';
			$extModelName = '__'.strtoupper($extModelName).'__';
			$condition = array(
					"this0.customer" => $category['customer'],
					"this0.is_deleted" => 0,
					"this0.category" => $cate
			);
			$m = M()->table("$tableName this0")->join("LEFT JOIN $extModelName this1 on this0.id=this1.id")->where($condition);
			$new_m = clone $m;
			if($paginate){
				$m->limit($pageSize)->page($p);
				$contentCount = $new_m->count();
			}
			$contentLists = $m->order('this0.update_time desc')->select();
			foreach ( $contentLists as $k => &$v ) {
				$v ['tags'] = $this->getTagNames ( $v ['tags'], $v['customer'] );
			}
			return array("data"=>$contentLists, "count"=>$contentCount, "model" => $model);
		} else return array();
	}
	
	
	// 获得标签名
	private function getTagNames($ids, $aid) {
		if ($ids) {
			$names = M ( "Tags" )->where ( array (
					"id" => array (
							"in",
							$ids
					),
					"cid" => $aid
			) )->getField ( "name", true );
					return join ( ',', $names );
		}
		return "";
	}
	
}